package com.vgemv.jsutilitysdk.SharedPreference;


import android.content.Context;
import android.content.SharedPreferences;

import com.vgemv.jsutilitysdk.JsJsonManager.JsJsonManager;

/**
 * 根据name可能有不同实例,所以,需要用实例方法.
 */
public class JsSharedPreferencesManager {
     private String mStr_name;
     private Context mContext;
    private SharedPreferences mSharedPreferences;

    static private JsSharedPreferencesManager _sharedInstance = null;

    //需要先调用初始化方法.
    //初始化的是单例对象.
    public static void initClass(Context context, String name) {
        _sharedInstance = new JsSharedPreferencesManager(context,name);
    }

    public static JsSharedPreferencesManager sharedInstance() {
        return _sharedInstance;
    }

    public JsSharedPreferencesManager(Context context,String name ){
        this.mContext = context;
        this.mStr_name = name;
        this.mSharedPreferences = context.getSharedPreferences(name,Context.MODE_PRIVATE);
    }


    /**
     * 将object转化为json字符串然后存储.
     * 如果object已经是字符串,则直接存储.
     * @param key
     * @param object
     */
    public void set(String key, Object object) {
        String json = null;
        if(object.getClass() == String.class) {
            json = (String)object;
        }
        else {
            json = JsJsonManager.toJson(object, false);
        }
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(key, json);
        editor.apply();
    }

    public  String get(String key) {
        String json = mSharedPreferences.getString(key, "");
        return json;
    }

    public  <T> T get(String key, Class<T> classOfT) {
        String json = mSharedPreferences.getString(key, "");
        if (json.length() == 0) {
            return null;
        }
        T obj = JsJsonManager.fromJson(json, classOfT);
        return obj;
    }

    /**
     * 清除key的内容.
     *
     * @param key
     */
    public void remove(String key) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.remove(key);
        editor.apply();
    }
}
